<script setup lang="ts">
import { addForm, sendSmsCode } from '@/api/modules/ad';
import { reactive,defineProps } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute()
const props = defineProps<{
  templateInfo?: any
}>()
const emit = defineEmits(['goToNext'])
const phoneReg = /^1[3-9]\d{9}$/
// 表单数据
const formData = reactive({
  phone: '',
  smsCode: ''
})

// toast状态
const toast = reactive({
  message: '',
  show: false
})

// 倒计时状态
const countDown = reactive({
  seconds: 0,
  isCounting: false
})
const sendCode=async ()=>{
  // 如果正在倒计时，则不执行后续操作
  if(countDown.isCounting){
    return
  }
  
  // 校验手机号
  if(!formData.phone){
    showToast('请输入手机号码')
    return
  }
  
  if(!phoneReg.test(formData.phone)){
    showToast('请输入正确的手机号码')
    return
  }
  try{
    await sendSmsCode({phone:formData.phone})
    // 显示发送成功提示
    showToast('验证码已发送')
    
    // 开始60秒倒计时
    countDown.seconds = 60
    countDown.isCounting = true
    
    const timer = setInterval(() => {
        countDown.seconds--
        
        // 倒计时结束
        if(countDown.seconds <= 0){
          clearInterval(timer)
          countDown.isCounting = false
        }
    }, 1000)
  }catch(err:any){
    showToast(err.msg)
  }
  
}
const submit=async ()=>{
  // 校验手机号
  if(!formData.phone){
    showToast('请输入手机号码')
    return
  }
  if(!phoneReg.test(formData.phone)){
    showToast('请输入正确的手机号码')
    return
  }
  
  // 校验验证码
  if(!formData.smsCode){
    showToast('请输入验证码')
    return
  }
  const option:any={
    ...route.query,
    source:route.query?.source,  //投放渠道
    planCode:route.query?.p_id,//计划id
    landingUrl:window.location.href,//原始落地页 URL（含追踪参数，如 bd_vid）
    phone:formData.phone,
    smsCode:formData.smsCode,
  }
  try{
    const res=await addForm(option)
    showToast(JSON.stringify(res))
    if(res.code===0){
        showToast('提交成功')
        emit('goToNext',{...res.data,phone:formData.phone,})
    }else{
        showToast(res.msg)
    }
  }catch(err:any){
    showToast(err.msg)
  }
}
const phoneChange=()=>{
    // 当手机号完全符合格式，且不在倒计时状态时，自动获取验证码
    if(phoneReg.test(formData.phone) && !countDown.isCounting) {
        // 延迟一小段时间再自动获取，避免用户还在输入时就触发
        setTimeout(() => {
            // 再次校验，确保在延迟期间没有变化
            if(phoneReg.test(formData.phone) && !countDown.isCounting) {
                sendCode()
            }
        }, 500)
    }
}
// 显示toast提示
const showToast = (message: string) => {
  toast.message = message
  toast.show = true
  
  // 2秒后自动隐藏
  setTimeout(() => {
    toast.show = false
  }, 2000)
}

// 暴露submit方法给父组件调用
defineExpose({
  submit
})
</script>

<template>
    <div class="bv">
        <div class="bodyView">
            <div class="input df">
                <img src="/phone.png" />
                <input v-model="formData.phone" type="tel" maxlength="11" placeholder="请输入手机号码" @input="phoneChange" />
            </div>
            <div class="input df">
                <img src="/code.png" />
                <input v-model="formData.smsCode" type="tel" maxlength="6" placeholder="请输入验证码" class="code" />
                <div 
                class="sendCodeView"
                :class="{ 'counting': countDown.isCounting }"
                @click="sendCode"
                >
                {{ countDown.isCounting ? `${countDown.seconds}秒后重试` : '获取验证码' }}
                </div>
            </div>
            <div class="btn"><button @click="submit"> {{props.templateInfo?.signupButtonText||'立即抢购'}} </button></div>
        </div>
        <div class="van-toast van-toast--middle van-toast--text" :style="{display: toast.show ? 'flex' : 'none' }">
        <div class="van-toast__text">{{ toast.message }}</div>
        </div>
    </div>
    
</template>

<style scoped lang="scss">
.bv {
  max-width: 100%;
  .df{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .bodyView{
    margin-top:0.5rem;
    padding-bottom:0.3rem;
    .input{
      width: 7.5rem;
      padding: 0 0.4rem;
      line-height: 1.2rem;
      margin: 0 auto 0.3rem;
      border-radius: 0.6rem;
      background-color: #f7f8fa;
      overflow: hidden;
      img{
        width: 0.48rem;
        display: block;
        max-width: 100%;
      }
      input{
        font-size: 0.4rem;
        flex: 1;
        text-indent: 1em;
        height: 1.2rem;
        background-color: transparent;
        outline: none;
        border: 0;
      }
      .sendCodeView{
        font-size: 0.32rem;
        color: #ec6235;
        width: 4rem;
        text-align: center;
        cursor: pointer;
      }
      .sendCodeView.counting{
        color: #999;
        cursor: not-allowed;
      }
    }
    .btn{
        text-align: center;
        button{
            width: 8.3rem;
            line-height: 1.2rem;
            height: 1.2rem;
            background: linear-gradient(0deg, #ff6c45, #f84101);
            border-radius: 0.6rem;
            font-size: 0.48rem;
            font-weight: 500;
            color: #fff;
            text-align: center;
            margin:0 auto;
            padding: 0;
            outline: none;
            border: 0;
        }
      
    }
  }
  .van-toast{
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 3000;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    box-sizing: content-box;
    width: 88px;
    max-width: 70%;
    min-height: 88px;
    padding: 16px;
    color: #fff;
    font-size: 14px;
    line-height: 20px;
    white-space: pre-wrap;
    text-align: center;
    word-wrap: break-word;
    background-color: rgba(0, 0, 0, .7);
    border-radius: 8px;
    -webkit-transform: translate3d(-50%, -50%, 0);
    transform: translate3d(-50%, -50%, 0);
    &.van-toast--text{
      width: -webkit-fit-content;
      width: fit-content;
      min-width: 96px;
      min-height: 0;
      padding: 8px 12px;
    }
  }
}


</style>